<?php
// +----------------------------------------------------------------------
// | Qbt CMS Plugin
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2018 http://www.qbt8.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 黄老邪 <develop02@qbt8.com>
// +----------------------------------------------------------------------
namespace plugins\qbt_graphical\controller;

use cmf\controller\PluginAdminBaseController;
use plugins\qbt_graphical\model\GraphicalConfigModel;
use think\Config;
use think\Db;

class AdminIndexController extends PluginAdminBaseController
{

    public function _initialize()
    {
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        } else {
            $this->error('未登录');
        }
    }

    /**
     * 统计管理
     * @adminMenu(
     *     'name'   => '统计报表',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '图形统计报表',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $lists = Db::name('graphical_config')->order('id desc')->select();
        $this->assign('lists', $lists);
        return $this->fetch('/admin_index');
    }

    //添加
    public function add()
    {
        if (request()->isPost()) {
            $data = input();
            $data_input = $data['post'];
            $model = new GraphicalConfigModel();
            $menu = array(
                'parent_id' => '121',
                'type' => '1',
                'status' => '1',
                'list_order' => '10000',
                'app' => 'plugin/QbtGraphical',
                'controller' => 'AdminIndex',
                'action' => 'statistics?name=' . $data_input['name'],
                'param' => '',
                'name' => $data_input['name'],
                'remark' => '',
            );
            if ($data_input['is_menu'] == 1) {
                $admin_menu = Db::name('admin_menu')->where('name', $data_input['name'])->find();
                if (empty($admin_menu)) {
                    Db::name('admin_menu')->insert($menu);
                } else {
                    $this->error('菜单名称已存在！请重新输入');
                }
            }else{
                $data_input['name']='多图表统计';
            }
            $id = $model->insertGetId($data_input);
            if ($id) {
                $this->success('添加成功', cmf_plugin_url('QbtGraphical://AdminIndex/index'));
            }
        }
        return $this->fetch('/admin_add');
    }

    //修改
    public function edit()
    {
        $model = new GraphicalConfigModel();
        if (request()->isPost()) {
            $data = input();
            $data_input = $data['post'];
            $data_input['name'] = $data_input['name'] ? $data_input['name'] : "";
            $menu = array(
                'parent_id' => '121',
                'type' => '1',
                'status' => '1',
                'list_order' => '10000',
                'app' => 'plugin/QbtGraphical',
                'controller' => 'AdminIndex',
                'action' => 'statistics?name=' . $data_input['name'],
                'param' => '',
                'name' => $data_input['name'],
                'remark' => '',
            );

            $Graphical_info = $model->where('id', input('id'))->find();
            if ($Graphical_info['is_menu'] == 1 && $data_input['is_menu'] == 1) {
                Db::name('admin_menu')->where('name', $Graphical_info['name'])->update(['name' => $data_input['name'],'action'=>'statistics?name=' . $data_input['name']]);
            } else {
                if ($data_input['is_menu'] == 1) {
                    $admin_menu = Db::name('admin_menu')->where('name', $data_input['name'])->find();
                    if (empty($admin_menu)) {
                        Db::name('admin_menu')->insert($menu);
                    } else {
                        $this->error('菜单名称已存在！请重新输入');
                    }
                } else {
                    $data_input['name']='多图表统计';
                    Db::name('admin_menu')->where('name', $Graphical_info['name'])->delete();
                }
            }
            $id = Db::name('graphical_config')->where('id', input('id'))->update($data_input);
            $this->success('修改成功', cmf_plugin_url('QbtGraphical://AdminIndex/index'));

        }
        $Graphical = $model->where('id', intval(input('id')))->find();
        return $this->fetch('/admin_edit', ['graphical' => $Graphical]);
    }

    //删除
    public function delete()
    {
        $model = new GraphicalConfigModel();
        if (intval(input('id'))) {
            $Graphical = $model->where('id', intval(input('id')))->find();
            if ($Graphical['is_menu'] == 1) {
                Db::name('admin_menu')->where('name', $Graphical['name'])->delete();
                $model->where('id', intval(input('id')))->delete();
                $this->success("删除成功！", '');
            } else {
                $model->where('id', intval(input('id')))->delete();
                $this->success("删除成功！", '');
            }
        } else {
            $this->error("id不能为空", '');
        }
    }

    //单图表列表
    public function statistics()
    {
        $model = new GraphicalConfigModel();

        $Graphical = $model->where(['name' => input('name'), 'is_menu' => 1])->find();
        $where = explode(',', $Graphical['where']);
        $where_in = [];
        if(!empty($where[0])){
            foreach ($where as $val) {
                $where_val = explode('=', $val);
                $where_in[$where_val[0]] = $where_val[1];
            }
        }

        $join = $Graphical['assistant_table'] . ' b';
        $join_where = 'b.' . $Graphical['assistant_table_id'] . '=' . 'a.' . $Graphical['main_table_id'];

        //X轴 为时间
        if ($Graphical['x_axis_val'] == 1) {
            //X轴时间为一周
            if ($Graphical['x_axis_time'] == 1) {
                //图表数据
                $endtime = strtotime('-1 day', strtotime(date('Y-m-d 23:59:59', time())));
                $starttime = strtotime('-1 day', $endtime) + 1;
                $d_list = [];
                $d_time = [];

                for ($i = 1; $i < 8; $i++) {
                    if ($i == 1) {
                        $d_time['date'] = $starttime;
                        if($Graphical['is_join']==1) {
                            $d_time['count'] = Db::name($Graphical['table'])->alias('a')->join($join,$join_where)->where([$Graphical['x_axis_field'] => array('between', [$starttime, $endtime])])->where($where_in)->count();
                        }else{
                            $d_time['count'] = Db::name($Graphical['table'])->alias('a')->where([$Graphical['x_axis_field'] => array('between', [$starttime, $endtime])])->where($where_in)->count();
                        }
                        $d_list [] = $d_time;
                    } else {
                        $end_time = strtotime('-' . ($i - 1) . 'day', $endtime);
                        $start_time = strtotime('-' . ($i - 1) . 'day', $starttime);
                        $d_time['date'] = $start_time;
                        if($Graphical['is_join']==1) {
                            $d_time['count'] = Db::name($Graphical['table'])->alias('a')->join($join,$join_where)->where([$Graphical['x_axis_field'] => array('between', [$start_time, $end_time])])->where($where_in)->count();
                        }else{
                            $d_time['count'] = Db::name($Graphical['table'])->alias('a')->where([$Graphical['x_axis_field'] => array('between', [$start_time, $end_time])])->where($where_in)->count();
                        }
                        $d_list [] = $d_time;
                    }
                }
                $d_list = $this->multi_array_sort($d_list, 'date', SORT_ASC);
                foreach ($d_list as $item) {
                    $date_name[] = date('Y-m-d', $item['date']);
                    $date_val[] = $item['count'];
                }
            } else {
                //图表数据  X轴时间为一个月之前的date('Y-m-t', strtotime('-1 month'))
                $endtime = strtotime(date('Y-m-t 23:59:59', strtotime('-1 month')));
                $starttime = strtotime('-1 day', $endtime) + 1;
                $d_list = [];
                $d_time = [];
                for ($i = 1; $i < date('t', strtotime(date('Y-m', strtotime("last month")))) + 1; $i++) {
                    if ($i == 1) {
                        $d_time['date'] = $starttime;
                        if($Graphical['is_join']==1) {
                            $d_time['count'] = Db::name($Graphical['table'])->alias('a')->join($join,$join_where)->where([$Graphical['x_axis_field'] => array('between', [$starttime, $endtime])])->where($where_in)->count();
                        }else{
                            $d_time['count'] = Db::name($Graphical['table'])->alias('a')->where([$Graphical['x_axis_field'] => array('between', [$starttime, $endtime])])->where($where_in)->count();
                        }
                        $d_list [] = $d_time;
                    } else {
                        $end_time = strtotime('-' . ($i - 1) . 'day', $endtime);
                        $start_time = strtotime('-' . ($i - 1) . 'day', $starttime);
                        $d_time['date'] = $start_time;
                        if($Graphical['is_join']==1) {
                            $d_time['count'] = Db::name($Graphical['table'])->alias('a')->join($join,$join_where)->where([$Graphical['x_axis_field'] => array('between', [$start_time, $end_time])])->where($where_in)->count();
                        }else{
                            $d_time['count'] = Db::name($Graphical['table'])->alias('a')->where([$Graphical['x_axis_field'] => array('between', [$start_time, $end_time])])->where($where_in)->count();
                        }
                        $d_time['count'] = Db::name($Graphical['table'])->where([$Graphical['x_axis_field'] => array('between', [$start_time, $end_time])])->count();
                        $d_list [] = $d_time;
                    }
                }
                $d_list = $this->multi_array_sort($d_list, 'date', SORT_ASC);
                foreach ($d_list as $item) {
                    $date_name[] = date('Y-m-d', $item['date']);
                    $date_val[] = $item['count'];
                }
            }
        } else {
            if ($Graphical['is_join'] == 1) {
//                echo $Graphical['table'];exit;
                $data_name_a = Db::name($Graphical['table'])->alias('a')
                    ->field($Graphical['x_axis_name'] . ',' . 'count(*)')
                    ->join($join, $join_where)
                    ->group($Graphical['x_axis_name'])
                    ->where($where_in)
                    ->select();

                foreach ($data_name_a as $item) {
                    $name = explode('.',$Graphical['x_axis_name']);
                    $date_name[] = $item[$name[1]];
                    $date_val[] = $item['count(*)'];
                }
            } else {
                $data_name_a = Db::name($Graphical['table'])->alias('a')
                    ->field($Graphical['x_axis_name'] . ',' . 'count(*)')
                    ->group($Graphical['x_axis_name'])
                    ->where($where_in)
                    ->select();
                foreach ($data_name_a as $item) {
                    $date_name[] = $item[$Graphical['x_axis_name']];
                    $date_val[] = $item['count(*)'];
                }
            }
        }
        return $this->fetch('/admin_statistics', ['data_name' => $date_name, 'data_val' => $date_val, 'graphical' => $Graphical]);
    }

    //多图表 列表
    public function multiple_statistics()
    {
        $model = new GraphicalConfigModel();
        $Graphical = $model->where(['is_menu' => 2])->select()->toArray();
        if (!empty($Graphical)) {
            $data_name_a=[];
            foreach ($Graphical as $item) {
                $where = explode(',', $item['where']);
                $where_in = [];
                if(!empty($where[0])){
                    foreach ($where as $val) {
                        $where_val = explode('=', $val);
                        $where_in[$where_val[0]] = $where_val[1];
                    }
                }
                if ($item['x_axis_val'] == 1) {
                //X轴时间为一周
                    if ($item['x_axis_time'] == 1) {
                        foreach ($where as $val) {
                            $where_val = explode('=', $val);
                            $where_in[$where_val[0]] = $where_val[1];
                        }
                        //图表数据
                        $endtime = strtotime('-1 day', strtotime(date('Y-m-d 23:59:59', time())));
                        $starttime = strtotime('-1 day', $endtime) + 1;
                        $d_list = [];
                        $d_time = [];
                        $join=[];
                        $join_where="";
                        if($item['is_join']==1){
                            $join = $item['assistant_table'] . ' b';
                            $join_where = 'b.' . $item['assistant_table_id'] . '=' . 'a.' . $item['main_table_id'];
                        }
                        for ($i = 1; $i < 8; $i++) {
                            if ($i == 1) {
                                $d_time['date'] = $starttime;
                                if($item['is_join']==1) {
                                    $d_time['count'] = Db::name($item['table'])->alias('a')->join($join,$join_where)->where([$item['x_axis_field'] => array('between', [$starttime, $endtime])])->where($where_in)->count();
                                }else{
                                    $d_time['count'] = Db::name($item['table'])->alias('a')->where([$item['x_axis_field'] => array('between', [$starttime, $endtime])])->where($where_in)->count();
                                }
                                $d_list [] = $d_time;
                            } else {
                                $end_time = strtotime('-' . ($i - 1) . 'day', $endtime);
                                $start_time = strtotime('-' . ($i - 1) . 'day', $starttime);
                                $d_time['date'] = $start_time;
                                if($item['is_join']==1) {
                                    $d_time['count'] = Db::name($item['table'])->alias('a')->join($join,$join_where)->where([$item['x_axis_field'] => array('between', [$start_time, $end_time])])->where($where_in)->count();
                                }else{
                                    $d_time['count'] = Db::name($item['table'])->alias('a')->where([$item['x_axis_field'] => array('between', [$start_time, $end_time])])->where($where_in)->count();
                                }
                                $d_list [] = $d_time;
                            }
                        }
                        $d_list = $this->multi_array_sort($d_list, 'date', SORT_ASC);
                        foreach ($d_list as $items) {
                            $date_name[] = date('Y-m-d', $items['date']);
                            $date_val[] = $items['count'];
                        }
                        $date_name_list=[];
                        foreach ($date_name as $k=>$val){
                            $date_name_list['name']=$date_name[$k];
                            $date_name_list['count_t']=$date_val[$k];
                            $data_name_a [$item['id']][] = $date_name_list;
                        }
                        unset($date_name);
                        unset($date_val);
                    } else {
                        //图表数据  X轴时间为一个月之前的date('Y-m-t', strtotime('-1 month'))
                        $endtime = strtotime(date('Y-m-t 23:59:59', strtotime('-1 month')));
                        $starttime = strtotime('-1 day', $endtime) + 1;
                        $d_list = [];
                        $d_time = [];
                        $join=[];
                        $join_where="";
                        if($item['is_join']==1){
                            $join = $item['assistant_table'] . ' b';
                            $join_where = 'b.' . $item['assistant_table_id'] . '=' . 'a.' . $item['main_table_id'];
                        }
                        for ($i = 1; $i < date('t', strtotime(date('Y-m', strtotime("last month")))) + 1; $i++) {
                            if ($i == 1) {
                                $d_time['date'] = $starttime;
                                if($item['is_join']==1) {
                                    $d_time['count'] = Db::name($item['table'])->alias('a')->join($join,$join_where)->where([$item['x_axis_field'] => array('between', [$starttime, $endtime])])->where($where_in)->count();
                                }else{
                                    $d_time['count'] = Db::name($item['table'])->alias('a')->where([$item['x_axis_field'] => array('between', [$starttime, $endtime])])->where($where_in)->count();
                                }
                                $d_list [] = $d_time;
                            } else {
                                $end_time = strtotime('-' . ($i - 1) . 'day', $endtime);
                                $start_time = strtotime('-' . ($i - 1) . 'day', $starttime);
                                $d_time['date'] = $start_time;
                                if($item['is_join']==1) {
                                    $d_time['count'] = Db::name($item['table'])->alias('a')->join($join,$join_where)->where([$item['x_axis_field'] => array('between', [$start_time, $end_time])])->where($where_in)->count();
                                }else{
                                    $d_time['count'] = Db::name($item['table'])->alias('a')->where([$item['x_axis_field'] => array('between', [$start_time, $end_time])])->where($where_in)->count();
                                }
                                $d_list [] = $d_time;
                            }
                        }
                        $d_list = $this->multi_array_sort($d_list, 'date', SORT_ASC);
                        foreach ($d_list as $items) {
                            $date_name[] = date('Y-m-d', $items['date']);
                            $date_val[] = $items['count'];
                        }
                        $date_name_list=[];
                        foreach ($date_name as $k=>$val){
                            $date_name_list['name']=$date_name[$k];
                            $date_name_list['count_t']=$date_val[$k];
                            $data_name_a [$item['id']][] = $date_name_list;
                        }
                        unset($date_name);
                        unset($date_val);
                    }
                } else {
                    if ($item['is_join'] == 1) {
                        $join = $item['assistant_table'] . ' b';
                        $join_where = 'b.' . $item['assistant_table_id'] . '=' . 'a.' . $item['main_table_id'];
                        $data_name_a[$item['id']] = Db::name($item['table'])->alias('a')
                            ->field($item['x_axis_name'] .' as name' . ',' . 'count(*) as count_t')
                            ->join($join, $join_where)
                            ->group($item['x_axis_name'])
                            ->where($where_in)
                            ->select()->toArray();
                    } else {
                        $data_name_a[$item['id']] = Db::name($item['table'])->alias('a')
                            ->field($item['x_axis_name'].' as name' . ',' . 'count(*) as count_t')
                            ->group($item['x_axis_name'])
                            ->where($where_in)
                            ->select()->toArray();
                    }
                }
            }
        } else {
            echo "客官别着急！先去插件中心里配置一点数据吧";
            exit;
        }
        return $this->fetch('/admin_multiple_statistics',[ 'graphical' => $Graphical,'data'=>$data_name_a]);
    }

    //数据排序
    public function multi_array_sort($arr, $shortKey, $short = SORT_DESC, $shortType = SORT_REGULAR)
    {
        if (!empty($shortKey)) {
            foreach ($arr as $key => $data) {
                $name[$key] = $data[$shortKey];
            }
            array_multisort($name, $shortType, $short, $arr);
        }
        return $arr;
    }

    //判断时间
    public function checkDateTime($date)
    {
        if (date('Y-m-d H:i:s', strtotime($date)) == $date) {
            return true;
        } else {
            return false;
        }
    }
}
